
class Playlist < Qt::ListView
	attr_reader :xmms
	attr_accessor :pitemlist

	slots 'playlistItemActivated(QListViewItem*)', 'playlistItemDoubleClicked(QListViewItem *, const QPoint &, int)',
		'highlightCurrent(int)', 'rmbClicked(QListViewItem *, const QPoint& , int)', 'playCurrentItem()',
		'deleteCurrentItem()', 'rehashPitemList()', 'printCurrentPlaylist()' 

	signals 'positionChanged(int)'

	def initialize(parrent)
		super
		@xmms=XmmsConnection.instance

		@client = MXmms2Client.instance

		@playpxmap = Qt::Pixmap.new($path+'icons/player_play.png')
		@pausepxmap =  Qt::Pixmap.new($path+'icons/player_pause')
		@pitemlist=[]

		addColumns
		fillPlaylist
		setAcceptDrops(true)
		viewport.setAcceptDrops(true)

		@dragobject = Qt::DragObject.new(self)
		@rmbmenu = Qt::PopupMenu.new(self)
		@rmbmenu.insertItem('Play', self, SLOT('playCurrentItem()'))
		@rmbmenu.insertItem('Delete', self, SLOT('deleteCurrentItem()'))
		connect(self, SIGNAL('contextMenuRequested( QListViewItem *, const QPoint& , int )'),
				     SLOT('rmbClicked(QListViewItem *, const QPoint& , int)'))
	
		connect(self, SIGNAL('returnPressed(QListViewItem*)'), SLOT('playlistItemActivated(QListViewItem*)'))
		connect(self, SIGNAL('doubleClicked(QListViewItem *, const QPoint &, int)'),
			SLOT('playlistItemDoubleClicked(QListViewItem *, const QPoint &, int)'))
		connect(self, SIGNAL('positionChanged(int)'), SLOT('highlightCurrent(int)'))

		@xmms.broadcast_playlist_changed.notifier { |res|
			case res.value[:type]
				when Xmms::Result::PLAYLIST_CHANGED_CLEAR
					clearPlaylist
				when Xmms::Result::PLAYLIST_CHANGED_ADD
					addPlaylistItem(res.value[:id],res.value[:position])
				when Xmms::Result::PLAYLIST_CHANGED_REMOVE
					position = res.value[:position]
					removePlaylistItem(position)
				when Xmms::Result::PLAYLIST_CHANGED_SHUFFLE
					rehashPitemList
					highlightCurrent(@nowplaying)
					puts "playlist shuffled, size: #{@pitemlist.length}"
				when Xmms::Result::PLAYLIST_CHANGED_MOVE
					from = res.value[:position]
					to = res.value[:newposition]
					movePlaylistItem(from, to)
					updatePositionColumn
					puts "#{res.value}"
				when Xmms::Result::PLAYLIST_CHANGED_INSERT
					puts res.value
			end
		}

		parent.handlePositionChange { |pos|
			@nowplaying =  pos
			emit positionChanged(pos)
		}
	end

	def playCurrentItem
		position = @pitemlist.index(currentItem)
		puts "playing position #{position}"
		@xmms.playlist_set_next(position).wait
		@xmms.playback_tickle.wait
	end

	def deleteCurrentItem
		position = @pitemlist.index(currentItem)
		puts "trying to remove position #{position}"
		@xmms.playlist_remove(position)
		@pitemlist.each { |item|
			item.setPixmap(1, Qt::Pixmap.new) if item
		}
	end

	def rmbClicked(item, point, i)
		@rmbmenu.popup(point) if item
	end

	def highlightCurrent(position)
		@pitemlist.each { |item|
			if item
				if item.text(0).strip == position.to_s
					item.setPixmap(1, @playpxmap)
					ensureItemVisible(item)
				else
					item.setPixmap(1, Qt::Pixmap.new)
				end
			end
		}
	end

	def updatePositionColumn
		maxposlen = @pitemlist.length.to_s.length
		@pitemlist.length.times {|x|
			if @pitemlist[x]
				str = x.to_s
				slen = str.length
				spaces = " " * (maxposlen - slen) 
				@pitemlist[x].setText(0, spaces+x.to_s)
			end
		}
		sort
	end

	def addPlaylistItem(id, pos)
		item = PlaylistItem.new(self, id)
		if  !@pitemlist[pos] 
			@pitemlist[pos] = item
		else
			@pitemlist.insert(pos, item)
		end
		updatePositionColumn
	end

	def removePlaylistItem(pos)
		takeItem(@pitemlist[pos])
		@pitemlist.delete_at(pos)
		updatePositionColumn
	end

	def movePlaylistItem(from, to)
		item = @pitemlist[from]
		@pitemlist.delete_at(from)
		@pitemlist.insert(to, item)
		updatePositionColumn
	end

	def printCurrentPlaylist
		@pitemlist.length.times { |x|
			if !@pitemlist[x]
				puts nil
			else
				puts "#{x}. #{@pitemlist[x].artist} -- #{@pitemlist[x].title}"
			end
		}
	end

	def fillPlaylist
		@xmms.playlist_list.notifier { |res|
			res.value.each_with_index { |id, pos|
				addPlaylistItem(id, pos)
			}
		}
	end

	def resizeEvent(event)
		width = (contentsRect.width - 80)/3
		setColumnWidth(0,0)
		setColumnWidth(1, width + 50)
		setColumnWidth(2, width - 25)
		setColumnWidth(3, width - 25)
		setColumnWidth(4, 60)
		repaintContents(contentsRect)
	end

	def dragObject
		return @dragobject
	end

	def rehashPitemList
		playlist = @xmms.playlist_list.wait.value
		newlist=[]
		counter=0
		playlist.each {|id|
			@pitemlist.each {|item|
				if !item.checked
					if id == item.xid
						item.checked = true
						newlist << item
						break
					end
				end
			}
		}
		@pitemlist.each { |item| item.checked = false}
		@pitemlist = newlist
		updatePositionColumn
	end

	def clearPlaylist
		@pitemlist.each { |y|
			takeItem(y)
		}
		@pitemlist=[]
	end

	def playlistItemActivated(item)
		id = item.xid
		artist = item.artist
		title = item.title
		position = @pitemlist.index(item)
		puts "activated position #{position}, trying to play"
		case @client.playbackstate
			when Xmms::Client::PLAY
				@xmms.playlist_set_next(position)
				@xmms.playback_tickle
			when Xmms::Client::STOP
				@xmms.playlist_set_next(position)
				@xmms.playback_tickle
				@xmms.playback_start
			when Xmms::Client::PAUSE
				@xmms.playlist_set_next(position)
				@xmms.playback_tickle
				@xmms.playback_start
		end
	end

	def playlistItemDoubleClicked(item, point, i)
		playlistItemActivated(item)
	end

	def addColumns
		addColumn('', 0)
		addColumn('Title')
		addColumn('Artist')
		addColumn('Album')
		addColumn('Length')
		setColumnWidthMode(1, Qt::ListView::Manual)
		setColumnWidthMode(2, Qt::ListView::Manual)
		setColumnWidthMode(3, Qt::ListView::Manual)
		setColumnWidthMode(4, Qt::ListView::Manual)
		setColumnAlignment(4, Qt::AlignRight)
		setMinimumWidth(400)
		setSortColumn(0)
		setResizeMode(Qt::ListView::NoColumn)
		setAllColumnsShowFocus(true)
		setHScrollBarMode(Qt::ScrollView::AlwaysOff)
	end
end

class PlaylistItem < Qt::ListViewItem
	attr_reader :xid, :artist, :title, :item, :srv, :len, :lenstr

	attr_accessor :checked

	def initialize(parent, id)
		@checked=false
		@xid = id
		@xmms = parent.xmms
		dict = @xmms.medialib_get_info(@xid).wait.value
		if dict[:chain] =~ /^curl/
			@artist, @title, @album = dict[:channel], dict[:title], nil
			@lenstr = '00:00'
		elsif dict[:chain] =~ /^file/ && dict[:title]
			@artist, @title, @album = dict[:artist], dict[:title], dict[:album]
			@len = dict[:duration].to_i/1000
			@lenstr = @len/3600 == 0 ? "%02d:%02d"%[(@len/ 60) % 60, @len % 60] :
				"%d:%02d:%02d"%[@len/3600, (@len/ 60) % 60, @len % 60]
		else
			@artist, @title, @album = dict[:url].split('/')[-1].gsub("+", " "), nil, nil
			@len = dict[:duration].to_i/1000
			@lenstr = @len/3600 == 0 ? "%02d:%02d"%[(@len/ 60) % 60, @len % 60] :
				"%d:%02d:%02d"%[@len/3600, (@len/ 60) % 60, @len % 60]
		end
		super(parent, 0.to_s, @title, @artist, @album, @lenstr)
		setDragEnabled(true)
		setDropEnabled(true)
	end

	def dropped(event)
		
	end

	def inspect
		return "[%s/%s] %s - %s"%[text(0), @xid, @artist, @title]
	end
	#redefined Qt::ListViewItem::key(int column, bool asc) for numerical sorting
	def key(column, asc)
		return "%08d"%[text(column).to_i]
	end
end
